/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.securityrat.servlet.dispatcher;

import com.securityrat.controller_temp.DatatypeFacade;
import com.securityrat.controller_temp.SystemFacade;
import com.securityrat.entities_temp.Perimetro;
import com.securityrat.entities_temp.RelSp;
import com.securityrat.entities_temp.System;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collection;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import php.java.servlet.RemoteHttpServletContextFactory;

/**
 *
 * @author p.vivoli
 */
@WebServlet(name = "FrontendServlet", urlPatterns = {"/FrontendServlet"})
public class FrontendServlet extends HttpServlet {
    //@PersistenceContext(unitName = "SecurityRATEngine-ejbPU")
//    private EntityManager em;
//    @Resource
//    private javax.transaction.UserTransaction utx;
    
    @EJB
    private DatatypeFacade datatypeFacade;
    @EJB
    private SystemFacade systemFacade;
    

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        
        //com.securityrat.entities.System sys = new com.securityrat.entities.System(2001);
         //sys.setNome("sistema422");
         //systemFacade.create(sys);
        //List<com.securityrat.entities.System> l = systemFacade.findAll();
                com.securityrat.entities_temp.System sys = systemFacade.find(1);
        
        
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet CreateSystem</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet CreateSystem at " + request.getContextPath() + "</h1>");
            
            out.println(sys.getNome());
//            out.println(sys.getPerimetroCollection().size());
//            for(Perimetro p : sys.getPerimetroCollection()) {
//                out.println("<b>ID </b>"+ p.getId());
//            }
            
            
            Collection<RelSp> perim_sys = sys.getRelSpCollection();
                for (RelSp rel_sp : perim_sys) {
                    Perimetro p = rel_sp.getPerimetro();
                    out.println("<b>ID </b>"+ p.getId());
                }
            
            
            out.println("<b>datatype:</b>" + sys.getIdDatatype().getDescrizione());
            
            // metodo getSystemCollection dell oggetto Datatype restituisce
            // l'elenco di entità System che hanno l'id datatype in questione.
            // sys.getIdDatatype() --> return oggetto Datatype con Id impostato al sistema sys
            out.println("<br>All</b>" + sys.getIdDatatype().getSystemCollection().size());
            
            
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    
    
    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    
    
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
         
         RemoteHttpServletContextFactory ctx = new RemoteHttpServletContextFactory(this, 
            getServletContext(), request, request, response);

          response.setHeader("X_JAVABRIDGE_CONTEXT", ctx.getId());
          response.setHeader("Pragma", "no-cache");
          response.setHeader("Cache-Control", "no-cache");

          try { 
            ctx.handleRequests(request.getInputStream(), response.getOutputStream()); 
          } finally { 
            ctx.destroy(); 
          }
    }
    

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
    
    
    
    // ------------------------------------------------
     public void addSystem() {
         com.securityrat.entities_temp.System sys = new com.securityrat.entities_temp.System(2001);
         sys.setNome("sistema424");
         systemFacade.create(sys);
    }
    
    public void delSystem() {
        systemFacade.remove(systemFacade.find(2));
    }
    
    
    public String getAllSystems() throws IOException {
      
        
       List<System> list = systemFacade.findAll();
       
       JSONArray systems = new JSONArray();
       JSONArray perimetriJson = null;
        //systems.add(new User(123,"foo1", "secret1"));
        //systems.add(new User(124,"foo2", "secret2"));
        //systems.add(new User(125,"\"foo2\"", "secret2"));
                
        JSONObject jsonobj = null;
        String tot = ""; 
        try
        {
            for (System s : list) {
                jsonobj = new JSONObject();
                jsonobj.put("id",s.getId().toString());  //id
                jsonobj.put("nome",s.getNome());  // nome
                jsonobj.put("descrizione", s.getDescrizione());
                jsonobj.put("stato", s.getStato());
                jsonobj.put("datatype", s.getIdDatatype().getDescrizione());
                
                perimetriJson = new JSONArray();
                
                /*
                 * Ciclo sui perimetri associati al sistema e 
                 * li inserisco in lista perimetri
                 */
                Collection<RelSp> perim_sys = s.getRelSpCollection();
                for (RelSp rel_sp : perim_sys) {
                    Perimetro p = rel_sp.getPerimetro();
                    perimetriJson.add(p.getDescrizione());
                }
                
                jsonobj.put("perimetri_lista",perimetriJson);
                
                systems.add(jsonobj);
                
            }
        }
        catch(Exception e)
        {
            return "error";
           
        } 

        
        
         StringWriter out = new StringWriter();
         systems.writeJSONString(out);
         //systems.writeJSONString(out);
         //System.out.println(out.toString());
         return out.toString();
        
    }
    
    
//    class System implements JSONStreamAware{
//        private String id;
//        private String name;
//        
//        
//        public System(String id, String name){
//                this.id = id;
//                this.name = name;
//           
//        }
//        
//       public void writeJSONString (Writer out) throws IOException{        
//                JSONObject jsonobj = new JSONObject();
//                jsonobj.put("id", id);
//                jsonobj.put("nome", name);
//                jsonobj.writeJSONString(out);
//                
////                LinkedHashMap obj = new LinkedHashMap();
////                obj.put("id", id);
////                obj.put("name", name);
////                JSONValue.writeJSONString(obj, out);
//       }
//    }
    
    
}
